// import Select from '../../../_antd1.11.2/Select';
// import Input from '../../../_antd1.11.2/Input';
// import Button from '../../../_antd1.11.2/Button';
// import Icon from '../../../_antd1.11.2/Icon';
// import Popover from '../../../_antd1.11.2/Popover';
import {Select, Input, Button, Icon, Popover} from 'antd';
import classNames from 'classnames';
import WeaTools from '../../wea-tools'
import forEach from 'lodash/forEach'
import isEmpty from 'lodash/isEmpty'
import debounce from 'lodash/debounce'
import trim from 'lodash/trim'
import isString from 'lodash/isString'
import isEqual from 'lodash/isEqual'
const Option = Select.Option;
import PureRenderMixin from 'react-addons-pure-render-mixin';
import OGroup from './OGroup';
import uniq from 'lodash/uniq';
import WeaHrmlist from '../../wea-hrmlist';
import { findDOMNode } from 'react-dom';

class main extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [],
            value: [],
            loading: false,
            focus: false,
            dropdownWidth: 200,
            hrmlist: [],
            hrmlistVisible: false,
        };
        this.selectedData = {};
    }
    componentWillReceiveProps(nextProps, nextState){
        this.props.isClearData !== nextProps.isClearData && this.clear();
        if (this.props.defaultFocus !== nextProps.defaultFocus && nextProps.defaultFocus) {
            this.setState({focus: true});
        }
    }
    shouldComponentUpdate(...args) {
        return PureRenderMixin.shouldComponentUpdate.apply(this, args);
    }
    // shouldComponentUpdate(nextProps,nextState) {
    //     return !isEqual(this.props.datas, nextProps.datas)
    //         || !isEqual(this.props.selectedValues, nextProps.selectedValues)
    //         || this.props.type !== nextProps.type
    //         || this.props.style !== nextProps.style
    //         || this.props.inputName !== nextProps.inputName
    //         || this.props.inputId !== nextProps.inputId
    //         || this.props.viewAttr !== nextProps.viewAttr
    //         || this.props.defaultFocus !== nextProps.defaultFocus
    //         || this.state.value !== nextState.value
    //         || !isEqual(this.state.data, nextState.data)
    //         || this.state.loading !== nextState.loading;
    // }
    componentDidUpdate() {
        const dom = this.refs.searchWrapperMui;
        if (this.state.focus) {
            $(dom).find('.ant-select-search--inline').css('minWidth', '10px');
            $(dom).find('input').focus();
        } else {
            $(dom).find('.ant-select-search--inline').css('minWidth', '0px');
        }
    }
    componentDidMount(){
        const {dropdownWidth} = this.state;
        const w = $(this.refs.searchWrapperMui).outerWidth();
        if (dropdownWidth < w) {
            this.setState({dropdownWidth: w});
        }
    }
    clear() {
        this.setState({data: []});
        this.selectedData = {};
    }
    isCrm() {
        const type = this.props.type || 1;
        return type === 1 || type === 17 || type === '1' || type === '17';
    }
    getData(name = '') {
        let {type, oldUrl, completeURL} = this.props;
        let url = completeURL || `/api/workflow/browser01/complete/${type}?`;
        type = type || 1;
        if (oldUrl) {
            url = `/api/ec/api/data/search?type=${type}&`;
        }
        if (trim(name)) {
            WeaTools.callApi(`${url}q=${encodeURIComponent(trim(name))}`,'GET').then((res)=> {
                let resD = isString(res.datas) && res.datas.length > 0? JSON.parse(res.datas): res.datas;
                if (oldUrl) resD = res;
                resD = resD || [];
                if (this.isCrm()) {
                    // 需要过滤已选中数据（部门，分组）
                    let filterDatas = [];
                    let selectIds = [];
                    const {datas, selectedValues} = this.props;
                    selectedValues && selectedValues.forEach(k => {
                        let target = datas[k];
                        if (target.type === 'resource') {
                            selectIds.push(target.id);
                        } else {
                            selectIds = selectIds.concat(k.split(','));
                        }
                    })
                    resD.forEach((item)=> {
                        item.type = 'resource';
                        item.nodeid = `resource_${item.id}x`;
                        item.lastname = item.name;
                        if (selectIds.indexOf(item.id) === -1) {
                            filterDatas.push(item);
                        }
                    })
                    resD = filterDatas;
                }
                this.setState({data: resD, loading: false, activeKey: this.getActiveKey(resD)});
            });
        } else {
            this.setState({data: [], loading: false, activeKey: ''});
        }
    }
    getActiveKey(data) {
        const {selectedValues = []} = this.props;
        let v = '';
        if (data && data.length > 0) {
            let target = data.filter((d) => selectedValues.indexOf(d.id) == -1);
            if (!isEmpty(target)) v = target[0].id;
        }
        return v;
    }
    getItemById(id) {
        const {data} = this.state;
        const {datas} = this.props;
        if (datas[id]) return datas[id];
        if (!isEmpty(data)) {
            for (let i = 0; i < data.length; i++) {
                if (id === data[i].id) return data[i];
            }
        }
    }
    handleChange(values) {
        this.selectedData = {};
        values.forEach((v)=> {
            let item = this.getItemById(v);
            if (item) this.selectedData[v] = item;
        });
        this.props.onChange && this.props.onChange(values, this.selectedData)
        if (this.hasAll() && values.length === 0) {
            this.props.dropAllUserGroup && this.props.dropAllUserGroup()
        }
        this.setState({activeKey: ''});
    }
    handleBlur() {
        this.setState({activeKey: ''});
        this.setState({data: []});
    }
    handleFocus() {
        this.setState({focus: true});
    }
    handleSearch(value) {
        const { type } = this.props;
        if (this.hasAll() || type === '141') {
            return;
        }
        this.setState({loading: true});
        this.getData(value);
    }
    handleClick() {
        const {datas, selectedValues} = this.props;
        if (this.props.clickCallback){
            if (this.hasAll()) {
                return;
            }
            this.props.clickCallback(selectedValues, datas);
        }
    }
    getName(item) {
        const {inputName} = this.props;
        let name;
        if (item) {
            if (this.isCrm()) {
                if (item.type === 'all') {
                    return `${item.lastname}(${item.count})`
                }
                if (item.type !== 'resource') {
                    return `${item.lastname}(${(item.users || []).length})`
                }
                name = item.lastname || item.name;
            } else {
                name = item[inputName] || item.name;
            }
        }
        return name;
    }
    selectedClickHandler(e, data) {
        let item;
        if (this.isReadOnly()) {
            item = data;
        } else {
            item = this.props.datas[data.key];
        }
        if (this.isCrm()) {
            if (item.type === 'resource') {
                window.openhrm(item.id);
                window.pointerXY(e.nativeEvent);
                return;
            }
            if (item.type !== 'resource' && item.type !== 'all') {
                let target = jQuery(e.nativeEvent.target);
                let parent = jQuery(this.refs.searchWrapperMui);
                let y = target.offset().top;
                let x = target.offset().left;
                let py = parent.offset().top;
                let px = parent.offset().left;
                let style = {
                    top: y - py + 25,
                    left: x - px,
                }
                if (!isEmpty(item.users)) {
                    this.setState({hrmlist: item.users, hrmlistVisible: true, hrmlistStyle: style});
                }
                e.stopPropagation && e.stopPropagation();
                e.preventDefault && e.preventDefault();
                e.nativeEvent && e.nativeEvent.preventDefault();
            }
        } else {
            const {linkUrl, inputId} = this.props;
            if (linkUrl) {
                let url = `${linkUrl}${item[inputId] || item.id}`
                window.open(url);
            }
        }
    }
    //只读
    isReadOnly() {
        const {viewAttr} = this.props;
        return viewAttr === 1 || viewAttr === '1';
    }
    // 处理所有人
    hasAll(){
        const {datas} = this.props;
        let tag = false;
        forEach(datas, (value, key)=> {
            if (value.type === 'all') {
                tag = true;
            }
        });
        return tag
    }
    addOnClick() {
        this.props.addOnClick && this.props.addOnClick();
    }
    countCrm() {
        const {datas, selectedValues} = this.props;
        let count = 0;
        let ids = [];
        selectedValues && selectedValues.forEach((v)=> {
            let item = datas[v];
            if (item.type === 'all') {
                count += item.count;
            } else if (item.type !== 'resource') {
                item.users && item.users.forEach((u)=> ids.push(u.id))
            } else {
                ids.push(item.id);
            }
        })
        count += uniq(ids).length;
        return count;
    }
    showCount() {
        let bool = false;
        const {datas, selectedValues} = this.props;
        let resources = [];
        let groups = [];
        selectedValues && selectedValues.forEach((v)=> {
            let item = datas[v];
            if (item.type === 'all') {
            } else if (item.type !== 'resource') {
                groups.push(item);
            } else {
                resources.push(item);
            }
        })
        if (groups.length > 1 ) bool = true;
        if (groups.length == 1 && resources.length > 0) bool = true;
        return bool;
    }
    render() {
        const {underline, fieldName, hasBorder, layout, style = {}, datas, selectedValues, viewAttr, maxBrowerHeight, resize, linkUrl, isDetail, hasAddBtn, hasAddGroup = false} = this.props;
        const {hrmVisible, dropdownWidth, activeKey} = this.state;
        const clsname = classNames({
            'required': (viewAttr === 3 || viewAttr === '3') && isEmpty(selectedValues),
            'mr12': /^field/.test(fieldName) || (viewAttr == '3' && isEmpty(selectedValues)),
            'resize': resize,
            'wea-associative-click': this.isCrm() || !isEmpty(linkUrl),
            'ext-btn': hasAddBtn || hasAddGroup,
            'border': hasBorder,
            'underline': underline,
        });
        style.textDecoration = 'none';
        const HrmListContent = (
            <WeaHrmlist
                list={this.state.hrmlist}
                onVisibleChange={(v)=> this.setState({hrmlistVisible: v})}
                style={this.state.hrmlistStyle}
                visible={this.state.hrmlistVisible} ref="weaHrmlist">
            </WeaHrmlist>
        );

        if (this.isReadOnly()) {
            let arr = [];
            selectedValues && selectedValues.map(v => {
                let item = this.getName(datas[v]);
                if (!isString(item)) {
                    arr.push(<a className="child-item cursor-pointer wdb"
                    onClick={(e) => this.selectedClickHandler(e, datas[v])}>{item}</a>)
                } else {
                    arr.push(<a className="child-item cursor-pointer wdb" onClick={(e) => this.selectedClickHandler(e, datas[v])} dangerouslySetInnerHTML={{__html: item}}>
                        </a>)
                }
            })
            return (
                <span id={`${this.props.fieldName}span`} className={`wea-associative-search wea-field-readonly ${clsname} ${this.props.cls||''}`} style={style} ref="searchWrapperMui" ref="searchWrapperMui">
                    {arr}
                    {this.isCrm() && this.showCount() && <span style={{color: '#bfbfc0'}}>(共{this.countCrm()}人)</span>}
                    <Popover placement="bottomLeft" title=""
                        trigger="click"
                        content={HrmListContent}
                        visible={this.state.hrmlistVisible}
                        onVisibleChange={(v)=> this.setState({hrmlistVisible: v})}
                        getTooltipContainer={()=> this.refs.searchWrapperMui}
                        overlayClassName="hrmlist-wrapper"
                    >
                        <div className="hrmlistDom">&nbsp;</div>
                    </Popover>
                </span>
            )
        }
        let options = this.state.data.map(d => d.id && <Option key={d.id} title={d.title || this.getName(d)}>{this.getName(d)}</Option>);
        selectedValues && selectedValues.map((v) => {
             v && options.unshift(<Option key={v} title={this.getName(datas[v])}>{this.getName(datas[v])}</Option>);
        });
        let select = <Select
            {...this.props}
            onInputBlur={()=> {this.setState({focus: false})}}
            maxHeight={maxBrowerHeight}
            hideSelected={true}
            transitionName=""
            animation=""
            defaultValue={selectedValues}
            value ={selectedValues}
            multiple={true}
            placeholder={this.props.placeholder}
            notFoundContent=""
            activeKey={activeKey}
            defaultActiveFirstOption={true}
            showArrow={false}
            filterOption={false}
            onFocus={this.handleFocus.bind(this)}
            onChange={this.handleChange.bind(this)}
            onSearch={debounce(this.handleSearch, 400).bind(this)}
            onBlur={this.handleBlur.bind(this)}
            selectedClickCB={this.selectedClickHandler.bind(this)}
            dropdownStyle={{minWidth: dropdownWidth}}
            getPopupContainer={() => this.props.getPopupContainer && this.props.getPopupContainer() || layout || this.refs.searchWrapperMui}
            >
                {options}
        </Select>

        const disabled = this.hasAll();

        const content = (
            <OGroup isshowoperategroup={hrmVisible} handleVisibleChange={this.handleVisibleChange.bind(this)} setOperatorIds={this.crmAddcb.bind(this)}/>
        );

        return (
            <div className={`wea-associative-search wea-associative-search-mult ${clsname}`} style={style} ref="searchWrapperMui">
                {select}
                <Icon type="loading" style={{display: this.state.loading ? 'block' : 'none'}} />
                <div className="ant-input-group-wrap">
                    {disabled?
                        <Button type="ghost" icon="search" disabled/>
                        :<Button type="ghost" icon="search" onClick={this.handleClick.bind(this)}/>
                    }
                </div>
                {
                    hasAddBtn &&
                    <div className="ant-input-group-wrap extbtn">
                        <Icon className="add-icon" type="plus" onClick={this.addOnClick.bind(this)}/>
                    </div>
                }
                {
                    this.isCrm() && hasAddGroup &&
                    <div className="ant-input-group-wrap extbtn hasAddGroup">
                        <Popover placement="bottomLeft" title=""
                            content={content} trigger="click"
                            visible={hrmVisible}
                            onVisibleChange={this.handleVisibleChange.bind(this)}
                            getTooltipContainer={()=> this.refs.searchWrapperMui}
                            >
                            {disabled?
                                <Button type="primary" title="快捷选择人员" size="small" disabled>
                                    <i className='icon-coms-HumanResources'/>
                                </Button>
                                :<Button type="primary" title="快捷选择人员" size="small" onClick={this.hrmOnClick.bind(this)}>
                                    <i className='icon-coms-HumanResources'/>
                                </Button>
                            }
                        </Popover>
                    </div>
                }
                <Popover placement="bottomLeft" title=""
                    trigger="click"
                    content={HrmListContent}
                    visible={this.state.hrmlistVisible}
                    onVisibleChange={(v)=> this.setState({hrmlistVisible: v})}
                    getTooltipContainer={()=> this.refs.searchWrapperMui}
                    overlayClassName="hrmlist-wrapper"
                >
                    <div className="hrmlistDom">&nbsp;</div>
                </Popover>
            </div>
        );
    }
    handleVisibleChange(visible) {
        this.setState({hrmVisible: visible});
    }
    hrmOnClick() {
        this.setState({hrmVisible: true})
    }
    crmAddcb(data) {
        let datas = [];
        if (data.isAllUser) {
            datas.push({
                type: 'all',
                count: data.count,
                ids: data.ids,
                lastname: '所有人'
            })
        } else {
            datas = data.datas;
        }
        this.props.appendSearchValues && this.props.appendSearchValues(datas, true);
    }
}
export default main;